// 传入秒数  返回 天 时 分 秒 对象
var setT,cur_arr,_that,is_test = false,down_time;

function getTimeStr(second){
  var obj = dateformat(second)
  let hours = parseInt(obj.hours)<10?('0'+obj.hours):obj.hours;
  let minute = parseInt(obj.minute)<10?('0'+obj.minute):obj.minute
  let second1 = parseInt(obj.second)<10?('0'+obj.second):obj.second
  return obj.m + '-' + obj.d + ' ' + hours + ':' + minute
}

function dateformat(second) {
  // 天数
  var date = new Date(second); 
  //年  
  var Y = date.getFullYear();  
  //月  
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);  
  //日  
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();  
  //时  
  var hours = date.getHours();  
  //分  
  var minute = date.getMinutes();  
  //秒  
  var second = date.getSeconds();
  return {
    y:Y,
    m:M,
    d:D,
    hours:hours,
    minute:minute,
    second:second,
  }
}

function countdown(that, total_micro_second,time_arr) {
  var total_micro_second = total_micro_second;
  _that = that;
  cur_arr = time_arr;
  // 当前时间
  var cur_time = dateformat(total_micro_second)
  var next_time = nextTime(cur_time,time_arr,total_micro_second)
  down_time = (next_time - total_micro_second) / 1000 
  if(down_time < 0){
    setTimeout(() => {
      countdown(that, total_micro_second,cur_arr)
    }, 3000);
    return;
  }
  is_test = true
  
  setFun();
}
function setFun(){
  down_time -= 1;
  // 小时
  var hr = Math.floor(down_time / 3600 % 24);
  if (hr < 10) {
    hr = "0" + hr;
  }
  // 分钟
  var min = Math.floor(down_time / 60 % 60);
  if (min < 10) {
    min = "0" + min;
  }
  // 秒
  var sec = Math.floor(down_time % 60);
  if (sec < 10) {
    sec = "0" + sec;
  }
  if(hr == '00'&&min=='00'&&sec=='00'){
    var timestamp = Date.parse(new Date());
    countdown(_that,timestamp,cur_arr)
  } else {
    _that.setData({
      hor:hr,
      min:min,
      sec:sec,
    })
  }
  clearTimeout(setT);
  setT = setTimeout(function () {
    setFun();
  }, 1000)
}
//当前时间点是否在开抢时间 若在则进入开抢倒计时 若不在则进入等待倒计时
function nextTime(cur_time,time_arr,total_micro_second){
  var cur_hour = cur_time.hours == 0 ? 24 : cur_time.hours
  var index = time_arr.indexOf(cur_hour)
  let next_hours;
  var nextDate = new Date(); //后一天
  if(index>-1){//开抢
    nextDate.setHours(cur_hour+1)
    nextDate.setMinutes(0)
    nextDate.setSeconds(0)
    _that.setData({
      is_bigin:true
    })
  } else {
    for(var i = 0; i < time_arr.length - 1; i++){
      if(cur_hour > time_arr[i]&&cur_hour < time_arr[i+1]){
        next_hours = time_arr[i+1]
      }
    }
    _that.setData({
      is_bigin:false
    })
    nextDate.setHours(next_hours)
    nextDate.setMinutes(0)
    nextDate.setSeconds(0)
  }
  _that.changeX();
  return nextDate.getTime();
}
module.exports = {
  countdown:countdown,
  dateformat:dateformat,
  getTimeStr:getTimeStr
}